package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.csp.sentinel.dashboard.rule.AbstractDynamicRuleProviderAndPublisher;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;

/**
* @Description: TODO
* @author blueice
* @date 2021年3月25日 下午2:42:55
*
*/
public abstract class AbstractNacosRuleProviderAndPublisher<T> extends AbstractDynamicRuleProviderAndPublisher<T>
{
    @Autowired
    private ConfigService configService;

    @Override
    public List<T> getRules(String appName) throws Exception {
        String rules = configService.getConfig(appName + ruleSuffix(),
            NacosConfig.GROUP_ID, 3000);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return super.decoder.convert(rules);
    }
    
    @Override
    public void publish(String app, List<T> rules) throws Exception
    {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        boolean success = configService.publishConfig(app + ruleSuffix(),
            NacosConfig.GROUP_ID, super.encoder.convert(rules));
        if(!success){
            throw new RuntimeException("publish to nacos fail");
        }
    }
}
